package com.jingyi.system.service.impl;

import com.jingyi.common.core.domain.entity.WxUser;
import com.jingyi.common.core.domain.entity.WxUserMedicalRecord;
import com.jingyi.common.enums.RecordState;
import com.jingyi.common.enums.StateEnum;
import com.jingyi.common.utils.DateUtils;
import com.jingyi.common.utils.spring.SpringUtils;
import com.jingyi.system.domain.ImportData;
import com.jingyi.system.mapper.WxUserMapper;
import com.jingyi.system.service.IWxUserMedicalRecordService;
import com.jingyi.system.service.IWxUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 微信患者用户 业务层处理
 *
 * @author jingyi
 */
@Service
public class WxUserServiceImpl implements IWxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private IWxUserMedicalRecordService wxUserMedicalRecordService;


    /**
     * 根据条件分页查询患者数据
     *
     * @param user 患者信息
     * @return 患者数据集合信息
     */
    @Override
    public List<WxUser> selectUserList(WxUser user) {
        List<WxUser> list = wxUserMapper.selectUserList(user);
        if(!Objects.isNull(list)){
            list.forEach(wxUser -> {
                wxUser.setMedicalRecords(wxUserMedicalRecordService.selectRecordByUserId(wxUser.getUserId()));
            });
        }
        return list;
    }

    /**
     * 查询所有患者
     *
     * @return 患者列表
     */
    @Override
    public List<WxUser> selectUserAll() {
        return wxUserMapper.selectUserAll();
    }

    /**
     * 通过患者ID查询患者
     *
     * @param userId 患者ID
     * @return 患者对象信息
     */
    @Override
    public WxUser selectUserById(Long userId) {
        WxUser wxUser = wxUserMapper.selectUserById(userId);
        Optional.ofNullable(wxUser).ifPresent(user -> {
            user.setMedicalRecords(wxUserMedicalRecordService.selectRecordByUserId(userId));
        });
        return wxUser;
    }

    /**
     * 通过患者openId查询患者
     *
     * @param openId 微信openId
     * @return 患者对象信息
     */
    @Override
    public WxUser selectUserByOpenId(String openId){
        WxUser wxUser = wxUserMapper.selectUserByOpenId(openId);
        Optional.ofNullable(wxUser).ifPresent(wxUser1 -> {
            wxUser1.setMedicalRecords(wxUserMedicalRecordService.selectRecordByUserId(wxUser.getUserId()));
        });
        return wxUser;
    }

    /**
     * 修改患者信息
     *
     * @param user 患者信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(WxUser user) {
        return wxUserMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserState(WxUser user) {
        return  wxUserMapper.updateUser(user);
    }

    /**
     * 新增患者信息
     *
     * @param user 患者信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(WxUser user) {
        return wxUserMapper.insertUser(user);
    }

    /**
     * 通过患者ID删除患者
     *
     * @param userId 患者ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        return wxUserMapper.deleteUserById(userId);
    }

    /**
     * 批量删除患者信息
     *
     * @param userIds 需要删除的患者ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        return wxUserMapper.deleteUserByIds(userIds);
    }

    /**
     * 患者状态统计
     *
     * @return
     */
    @Override
    public Map<String, Object> getStatistic() {
        //系统总人数
        WxUser user = new WxUser();
        int allCount = wxUserMapper.getCount(user);
        //本周新增用户
        Map<String,Object> param = new HashMap<>();
        param.put("beginTime", DateUtils.getString(DateUtils.addDays(DateUtils.getNowDate(),-7),DateUtils.YYYY_MM_DD_HH_MM_SS));
        param.put("endTime",DateUtils.getString(DateUtils.getNowDate(),DateUtils.YYYY_MM_DD_HH_MM_SS));
        user.setParams(param);
        int weekCount = wxUserMapper.getCount(user);
        //本周已处理
        user.setState("1");
        int weekDealCount = wxUserMapper.getCount(user);
        //本周待处理
        String[] stateList = {"0","2"};
        param.put("stateList",Arrays.asList(stateList));
        user.setParams(param);
        user.setState(null);
        int weekUnDealCount = wxUserMapper.getCount(user);
        Map<String,Object> result = new HashMap<>();
        result.put("allCount",allCount);
        result.put("weekDealCount",weekDealCount);
        result.put("weekCount",weekCount);
        result.put("weekUnDealCount",weekUnDealCount);
        return result;
    }

    /**
     * 通过根据条件查询患者信息
     *
     * @param user 患者信息
     * @return 结果
     */
    @Override
    public WxUser getByMap(WxUser user) {
        WxUser wxUser = wxUserMapper.getByMap(user);
        Optional.ofNullable(wxUser).ifPresent(wxUser1 -> {
            wxUser1.setMedicalRecords(wxUserMedicalRecordService.selectRecordByUserId(wxUser1.getUserId()));
        });
        return wxUser;
    }

    @Override
    @Transactional
    public void importData(ImportData importData) {
        WxUser wxUser = new WxUser();
        BeanUtils.copyProperties(importData,wxUser);
        wxUser.setState("0");
        WxUser oldUser = SpringUtils.getAopProxy(this).selectUserByOpenId(importData.getOpenId());
        if(Objects.isNull(oldUser)){
            wxUser.setCreateBy("微信接口同步");
            insertUser(wxUser);
        }else{
            wxUser.setUserId(oldUser.getUserId());
            wxUser.setCode(oldUser.getCode());
            wxUser.setOpenId(oldUser.getOpenId());
            wxUser.setUpdateBy("微信接口同步");
            updateUser(wxUser);
        }
        WxUserMedicalRecord wxUserMedicalRecord = new WxUserMedicalRecord();
        BeanUtils.copyProperties(importData,wxUserMedicalRecord);
        wxUserMedicalRecord.setUserId(wxUser.getUserId());
        wxUserMedicalRecord.setState("0");
        wxUserMedicalRecord._setMedicalHistoryDesc();

        WxUserMedicalRecord recordVo = new WxUserMedicalRecord();
        String[] states = {RecordState.NOT_AUDIT.getCode(),RecordState.SUPPLEMENT.getCode()};
        Map<String,Object> map = new HashMap<>();
        map.put("stateList", Arrays.asList(states));
        recordVo.setParams(map);
        recordVo.setUserId(wxUser.getUserId());
        WxUserMedicalRecord oldRecord = wxUserMedicalRecordService.getByMap(recordVo);
        if(Objects.isNull(oldRecord)){
            wxUserMedicalRecord.setUpdateBy("微信接口同步");
            wxUserMedicalRecordService.insertRecord(wxUserMedicalRecord);
        }else{
            wxUserMedicalRecord.setRecordId(oldRecord.getRecordId());
            wxUserMedicalRecord.setCode(oldRecord.getCode());
            wxUserMedicalRecord.setCreateBy("微信接口同步");
            wxUserMedicalRecordService.updateRecord(wxUserMedicalRecord);
        }
    }

    @Override
    public WxUser insertOrUpdateByOpenId(WxUser user) {
        WxUser oldUser = SpringUtils.getAopProxy(this).selectUserByOpenId(user.getOpenId());
        if(Objects.isNull(oldUser)){
            user.setCreateBy("微信接口同步");
            user.setState(StateEnum.INITIAL.getCode());
            insertUser(user);
        }else{
            user.setUserId(oldUser.getUserId());
            user.setCode(oldUser.getCode());
            user.setUpdateBy("微信接口同步");
            updateUser(user);
        }
        return user;
    }
}
